package com.hygj.realm;

import com.hygj.pojo.*;
import com.hygj.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author hygl
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleAuthService roleAuthService;

    /**
     * Shiro身份登录认证 原理： 1、用户提交 用户名和密码 --- 2、shiro 封装令牌 ---- 3、realm 通过用户名将密码查询返回
     * ---- 4、shiro 自动去比较查询出密码和用户输入密码是否一致---- 5、进行登陆控制
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        // 获取基于用户名和密码的令牌
        // 实际上这个【authcToken】是从【UserController】里面 【currentUser.login(token);】传过来的
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        //System.out.println("-----用户名：" + token.getUsername());
        //System.out.println("-----密码：" + token.getPassword().toString());
        // 根据用户名去查找对象
        User user = userService.findUserByLoginName(token.getUsername());
        //System.out.println(user);
        if (user == null) {
            //System.out.println("用户不存在！");
            throw new AuthenticationException("用户不存在");
        }
        // 把管理员信息存入到Sesion中
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        String username = user.getUsername();
         String password = user.getPassword();
        //此处无需比对,比对的逻辑Shiro会做,
        //我们只需返回一个和令牌相关的正确的验证信息
        AuthenticationInfo info = new SimpleAuthenticationInfo(username, password, "");
        return info;
    }

    /**
     * 授权认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("-------------授权启动-------------");
        //通过身份，获取帐号名称
        String username = (String) principals.getPrimaryPrincipal();
        //通过账号名字 在用户表User中查询账号的id
        User user = userService.findUserByLoginName(username);
        //通过user得到rid
        int uid = user.getUid();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uid", uid);
        //获取帐号角色,用得到的用户uid去关联表userRole 表中，查询角色名称和角色ID
        UserRole listRoles = userRoleService.queryRoleByUserId(uid);
        int rid = listRoles.getRid();
        Set<Role> roleLists = roleService.selectRoles(rid);

        RoleAuth roleAuths = roleAuthService.selectAuthIds(rid);
        int  authId = roleAuths.getAuthId();
        List<Auth> authLists = authService.selectAuths(authId);
        Set<String> roles = new HashSet<String>();
        Set<String> auths = new HashSet<String>();

            /*roles.add(r.getRole_name());*/

        for(Auth r:authLists){
            auths.add(r.getAuthName());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.addStringPermissions(auths);

        /*SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);*/

        return info;
    }

}
